﻿using Dapper;
using Entity;
using ServiceCore;
using ServiceCore.Tool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Customer.Bussiness_Service
{

    public interface Iuser_service
    {
        ResultListModel<rk_user_search> get_pagelist(Base_List_Params query);
        ResultModel save_item(rk_user model);
        ResultModel set_wx_bind(string uid, string openid, string unionid, string wx_name, string headimg);

        ResultModel set_wx_unbind(string uid, string openid);
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="newpwd"></param>
        /// <returns></returns>
        ResultModel change_pwd(string newpwd, bool CheckOldpwd = false, string oldpwd = ""); 
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="newpwd"></param>
        /// <returns></returns>
        ResultModel change_pwd_web(string oldpwd, string newpwd);
    }
    public class user_service: Iuser_service
    {
        private readonly IToole_DI _tool;
        public user_service(IToole_DI Tool)
        {
            _tool = Tool;
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<rk_user_search> get_pagelist(Base_List_Params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<rk_user_search>>(result =>
            {
                string sql = "select a.*,b.role_name from rk_user a left join rk_role b on a.role_id=b.rid";
                string where = " where 1=1 ";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (!string.IsNullOrWhiteSpace(query.SerchKeyword))
                {
                    where += $" and (a.login_name like @SerchKeyword or a.u_name like @SerchKeyword or a.wx_tel like @SerchKeyword)";
                    query_dy.SerchKeyword = $"%{query.SerchKeyword}%";
                }
                result = _tool.di_db.GetPageList<rk_user_search>(sql, where, "a.uid", query_dy, query.IsPage, query.page, query.pagesize);
                return result;
            });
        } 
        /// <summary>
        /// 保存用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultModel save_item(rk_user model)
        {
            ResultModel result = new ResultModel();
            try
            {
                #region  基础验证 
                if (string.IsNullOrWhiteSpace(model.uid))
                {
                    model.uid = "";
                }
                if (string.IsNullOrWhiteSpace(model.login_name))
                {
                    result.code = 1;
                    result.msg = "登录名不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.u_name))
                {
                    result.code = 1;
                    result.msg = "姓名不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.link_phone))
                {
                    result.code = 1;
                    result.msg = "联系电话不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.role_id))
                {
                    result.code = 1;
                    result.msg = "请选择角色";
                    return result;
                }
                //if (string.IsNullOrWhiteSpace(model.wx_name))
                //{
                //    result.code = 1;
                //    result.msg = "微信名不能为空";
                //    return result;
                //} 
                //if (string.IsNullOrWhiteSpace(model.wx_no))
                //{
                //    result.code = 1;
                //    result.msg = "微信号不能为空";
                //    return result;
                //}
                var ExistModel = _tool.di_db.GetModel<rk_user>(new string[] { "u_name=@u_name", "uid<>@uid" }, model);
                if (ExistModel != null)
                {
                    result.code = 1;
                    result.msg = "角色名称已存在";
                    return result;
                }
                #endregion
                #region 数据处理 
                if (string.IsNullOrWhiteSpace(model.uid))
                {
                    if (string.IsNullOrWhiteSpace(model.login_pwd))
                    {
                        result.code = 1;
                        result.msg = "必须设置密码";
                        return result;
                    }
                    string savePwd = SecurityToMd5.Start(model.login_pwd + "^_^");
                    model.login_pwd = savePwd;
                    //添加
                    model.uid = _tool.di_getid.IGet_SnowFlake_Id;
                    model.addtime = DateTime.Now;
                    model.lastLoginTime = DateTime.Now;
                    string error = "";
                    int resultCount = _tool.di_db.StartTran((conn, tran) =>
                    {
                        int tranrow = 0;
                        tranrow += conn.Execute(_tool.di_db.AddBySqlStr<rk_user>(), model, tran);
                        return tranrow;
                    }, ref error);
                    if (resultCount > 0)
                    {
                        result.code = 0;
                        result.msg = "添加成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "添加失败 DB error=>" + error;
                    }
                }
                else
                {
                    //编辑
                    var needupdate = _tool.di_db.GetModel<rk_user>(new string[] { "uid=@uid" }, new { model.uid });
                    if (needupdate == null)
                    {
                        result.code = 1;
                        result.msg = "修改信息不存在";
                        return result;
                    }
                    if (!string.IsNullOrWhiteSpace(model.login_pwd))
                    {
                        //当前修改了密码
                        string savePwd = SecurityToMd5.Start(model.login_pwd + "^_^");
                        model.login_pwd = savePwd;
                    }
                    else {
                        model.login_pwd = needupdate.login_pwd;
                    } 
                    string error = "";
                    int resultCount = _tool.di_db.StartTran((conn, tran) =>
                    {
                        int tranrow = 0;
                        tranrow += conn.Execute(_tool.di_db.UpdateBySqlstr<rk_user>(new string[] { "login_name", "u_name", "login_pwd", "link_phone", "role_id", "wx_tel", "wx_no", "isuse" }, new string[] { "uid=@uid" }), model, tran);
                        return tranrow;
                    }, ref error);
                    if (resultCount > 0)
                    {
                        result.code = 0;
                        result.msg = "修改成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "修改成功 DB error";
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ResultModel set_wx_bind(string uid, string openid, string unionid, string wx_name, string headimg)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {
                if (string.IsNullOrWhiteSpace(openid))
                {
                    result.code = 1;
                    result.msg = "未能获取openid";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(uid))
                {
                    result.code = 1;
                    result.msg = "未能获取绑定员工ID";
                    return result;
                }
                rk_user uinfo = _tool.di_db.GetList<rk_user>("select top 1 * from rk_user where uid=@uid", new { uid }).FirstOrDefault();
                if (uinfo == null)
                {
                    result.code = 1;
                    result.msg = "绑定员工不存在";
                    return result;
                }
                if (!string.IsNullOrWhiteSpace(uinfo.bindOpenid))
                {
                    result.code = 1;
                    result.msg = "当前账户已绑定微信";
                    return result;
                }
                //更新信息
                int bindinfo = _tool.di_db.do_Execute("update rk_user set bindOpenid=@openid,bindUnionid=@unionid,wx_name=@wx_name,headimg=@headimg where uid=@uid", new
                {
                    uid,
                    openid,
                    unionid,
                    wx_name,
                    headimg
                });
                if (bindinfo > 0)
                {
                    result.code = 0;
                    result.msg = "绑定成功";
                }
                else {
                    result.code = 1;
                    result.msg = "绑定失败，没有项被改变";
                }
                return result;
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ResultModel set_wx_unbind(string uid,string openid)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {
              
                if (string.IsNullOrWhiteSpace(uid))
                {
                    result.code = 1;
                    result.msg = "未能获取解绑员工ID";
                    return result;
                }
                rk_user uinfo = _tool.di_db.GetList<rk_user>("select top 1 * from rk_user where uid=@uid", new { uid }).FirstOrDefault();
                if (uinfo == null)
                {
                    result.code = 1;
                    result.msg = "解绑员工不存在";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(uinfo.bindOpenid))
                {
                    result.code = 1;
                    result.msg = "用户已解绑";
                    return result;
                }
                if (uinfo.bindOpenid != openid)
                {
                    result.code = 1;
                    result.msg = "您不能解绑其他人的账号";
                    return result;
                } 
                //更新信息
                int bindinfo = _tool.di_db.do_Execute("update rk_user set bindOpenid=null,bindUnionid=null,wx_name=null,headimg=null where uid=@uid", new
                {
                    uid,
                });
                if (bindinfo > 0)
                {
                    result.code = 0;
                    result.msg = "解绑成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "没有数据被改变";
                }
                return result;
            });
        }


        public ResultModel change_pwd_web(string oldpwd, string newpwd)
        {
            return change_pwd(newpwd, true, oldpwd);
        }


        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public ResultModel change_pwd(string newpwd,bool CheckOldpwd = false,string oldpwd = "")
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {

                if (string.IsNullOrWhiteSpace(newpwd))
                {
                    result.code = 1;
                    result.msg = "请输入修改密码";
                    return result;
                }
                if (_tool.di_user.USER == null)
                {
                    result.code = 1;
                    result.msg = "你token呢？ 你特么的token呢?";
                    return result;
                }
                rk_user uinfo = _tool.di_db.GetList<rk_user>("select top 1 * from rk_user where uid=@uid", new { _tool.di_user.USER.uid }).FirstOrDefault();
                if (uinfo == null)
                {
                    result.code = 1;
                    result.msg = "您不存在...虽然不知道为什么 你为啥不存在呢..";
                    return result;
                }
                if (CheckOldpwd)
                {
                    if (string.IsNullOrWhiteSpace(oldpwd))
                    {
                        result.code = 1;
                        result.msg = "请输入旧密码";
                        return result;
                    }
                    else {
                        string old_pwd = SecurityToMd5.Start(oldpwd + "^_^");
                        if (old_pwd != uinfo.login_pwd)
                        {
                            result.code = 1;
                            result.msg = "旧密码验证失败";
                            return result;
                        }
                    }
                }
                string savePwd = SecurityToMd5.Start(newpwd + "^_^");
                //更新信息
                int bindinfo = _tool.di_db.do_Execute("update rk_user set login_pwd=@newpwd where uid=@uid", new { newpwd = savePwd, _tool.di_user.USER.uid });
                if (bindinfo > 0)
                {
                    result.code = 0;
                    result.msg = "修改成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "修改失败";
                }
                return result;
            });
        }

    }
}
